package com.work.dyduser.module.fragment;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.work.dyduser.R;
import com.work.dyduser.base.BaseFragment;
import com.work.dyduser.cache.Ckey;
import com.work.dyduser.cache.SPutils;
import com.work.dyduser.module.homepage.CaptureActivity;
import com.work.dyduser.utils.LogUtils;
import com.work.dyduser.utils.UIUtils;

import static com.work.dyduser.module.homepage.CaptureActivity.INTENT_EXTRA_KEY_QR_SCAN;

/**
 * @author WZ 2016/12/3
 * 首页
 */
public class HomePageFragment extends BaseFragment {

    private static final int REQUEST_CODE = 111;
    private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0x03;
    private ImageView imageqrcode;
    private String codenumber;
    private EditText tv_result;
    private TextView tv_result2;
    private String qrcode;
    private RelativeLayout rt_window;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home_fragment;
    }

    @Override
    protected void initView() {
//        // queryAndLoadNewPatch不可放在attachBaseContext 中，否则无网络权限，建议放在后面任意时刻，如onCreate中
//        SophixManager.getInstance().queryAndLoadNewPatch();
        rt_window = (RelativeLayout) findViewById(R.id.rt_window);
        imageqrcode = (ImageView) findViewById(R.id.iv_qrcode);
        tv_result = (EditText) findViewById(R.id.tv_result);
        tv_result2 = (TextView) findViewById(R.id.tv_result2);
    }

    @Override
    protected void initData() {
        super.initData();
        imageqrcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                autoObtainCameraPermission();
            }
        });
//        tv_result2.setText("当前版本:" + TelManagerUtils.getVersion(getActivity()) + "热修复测试");

        tv_result2.setText("请扫描二维码,然后拍视频上传二维码张贴位置");
        tv_result.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                SPutils.put(Ckey.USERID, s.toString());
                LogUtils.d("onTextChanged=" + s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                LogUtils.d("afterTextChanged=" + s.toString());
            }
        });


        rt_window.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HideKeyboard(v);
            }
        });
    }

    /***
     * 关软件盘
     *
     * @param v
     */
    public void HideKeyboard(View v) {
        if (v != null) {
            InputMethodManager imm = (InputMethodManager) v.getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm.isActive()) {
                imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);

            }
        }
    }

    /**
     * 自动获取相机权限
     */
    private void autoObtainCameraPermission() {
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
                UIUtils.showToast("您已经拒绝过一次");
            }
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, CAMERA_PERMISSIONS_REQUEST_CODE);
        } else {//有权限直接调用系统相机拍照
            openQrcode();
        }
    }

    private void openQrcode() {
        //打开二维码扫描界面
        Intent intents = new Intent(getContext(), CaptureActivity.class);
        startActivityForResult(intents, REQUEST_CODE);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case CAMERA_PERMISSIONS_REQUEST_CODE://调用系统相机申请拍照权限回调
                openQrcode();
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                codenumber = data.getStringExtra(INTENT_EXTRA_KEY_QR_SCAN);
                String[] arr = codenumber.split("=");
                if (arr != null) {
                    qrcode = arr[arr.length - 1];
                    SPutils.put(Ckey.USERID, qrcode);
                    tv_result.setText(qrcode + "");
                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        tv_result.setText(SPutils.get(Ckey.USERID));
    }

}
